package com.kujie.ai.controller;

import com.kujie.ai.dify.api.DifyChatSseApi;
import com.kujie.ai.dify.core.EnableDifyApi;
import com.kujie.ai.dify.enums.DifyResponseModeEnum;
import com.kujie.ai.dify.request.DifyChatRequest;
import com.kujie.ai.utils.AnswerCleaner;
import com.kujie.ai.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

@Slf4j
@RestController
@EnableDifyApi
@RequestMapping("/dify")
public class DifyController {

    private final String USER = "checkcheck1@163.com";

    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> chat(@RequestParam("input") String input) {

        log.info("Received chat request with input: {}", input);

        DifyChatSseApi difyChatSseApi = SpringUtils.getBean(DifyChatSseApi.class);

        DifyChatRequest request = DifyChatRequest.builder()
                .user(USER)
                .query(input)
                .responseMode(DifyResponseModeEnum.streaming)
                .build();

        return difyChatSseApi.chatSse(request)
                .filter(sse -> sse.answer() != null && !sse.answer().isEmpty())
                .map(sse -> AnswerCleaner.cleanAnswer(sse.answer()))
                .doOnError(error -> log.error("Error during chat: ", error))
                .onErrorResume(error -> {
                    log.error("Error in chat endpoint: ", error);
                    return Flux.just("Sorry, an error occurred while processing your request.");
                });
    }
}
